#include "LoopContrller.h"

static void OnStop(uv_async_t* async)
{
	((LoopContrller*)(async->data))->OnStopLoop();
}

void  LoopContrller::OnStopLoop()
{
	if (0 == uv_is_closing((uv_handle_t*)(&m_uvStopAsync)))
	{
		uv_close((uv_handle_t*)(&m_uvStopAsync), NULL);
	}	
	uv_stop(m_loop);
}

LoopContrller& LoopContrller::Getinstance()
{
	static LoopContrller loopContr;
	return loopContr;
}


LoopContrller::LoopContrller()
{
	m_loop = uv_default_loop();
	m_uvStopAsync.data = this;
	uv_async_init(m_loop, &m_uvStopAsync, OnStop);
}


LoopContrller::~LoopContrller()
{
}

void LoopContrller::StartRun()
{
	if (m_bRun)
	{
		return;
	}
	m_bRun = true;
	uv_run(m_loop, UV_RUN_DEFAULT);
}
void LoopContrller::StopRun()
{
	m_bRun = false;
	uv_async_send(&m_uvStopAsync);
	uv_loop_close(m_loop);	
}
